const path = require('path');
const fse = require('fs-extra');

const oTemp = path.join(__dirname, '../public/temp');

const mergeHandler = async (req, res, next) => {
  try {
    const { md5, name } = req.params;
    const mergeDir = `${oTemp}/${md5}`;

    const isExistDir = await fse.pathExists(mergeDir);
    if (!isExistDir) {
      res.json({
        code: 0,
        msg: '未找到合并项',
        data: null,
      });
      return;
    }

    const aFilePath = await fse.readdir(mergeDir);
    const targetPath = path.join(__dirname, '../public/zip', name);
    const isTargetFile = await fse.pathExists(targetPath);
    if (isTargetFile) {
      aFilePath.forEach(item => {
        fse.unlinkSync(`${mergeDir}/${item}`);
      });
      // 删除空目录
      await fse.rmdir(mergeDir);
      res.json({
        code: 0,
        msg: '合并项已存在',
        data: {
          url: `http://localhost:7003/zip/${name}`,
        },
      });
      return;
    }

    const aChunkPaths = aFilePath.map(item => `${mergeDir}/${item}`);
    // 目标流
    const targetStream = fse.createWriteStream(targetPath);
    const readStream = (chunkArray, cb) => {
      // 拿到第一个chunk
      const chunkPath = chunkArray.shift();
      const originStream = fse.createReadStream(chunkPath);
      originStream.pipe(targetStream, { end: false });
      originStream.on('end', () => {
        // 删除文件
        fse.unlinkSync(chunkPath);
        if (chunkArray.length > 0) {
          readStream(chunkArray);
        } else {
          // 删除空目录
          fse.rmdirSync(mergeDir);
        }
        if (cb) cb();
      });
    };
    readStream(aChunkPaths);

    res.json({
      code: 0,
      msg: 'multer上传方式',
    });
  } catch (error) {
    next(error);
  }
};

module.exports = mergeHandler;
